package com.atguigu.service.impl;

import com.atguigu.base.BaseMapper;
import com.atguigu.base.BaseServiceImpl;
import com.atguigu.entity.Admin;
import com.atguigu.entity.Role;
import com.atguigu.mapper.AdminMapper;
import com.atguigu.mapper.AdminRoleMapper;
import com.atguigu.mapper.RoleMapper;
import com.atguigu.service.AdminService;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Date:2022/10/31
 * Author:ybc
 * Description:
 */

@DubboService
public class AdminServiceImpl extends BaseServiceImpl<Admin> implements AdminService {

    @Autowired
    private AdminMapper adminMapper;
    @Autowired
    private RoleMapper roleMapper;
    @Autowired
    private AdminRoleMapper adminRoleMapper;

    @Override
    public BaseMapper<Admin> getBaseMapper() {
        return adminMapper;
    }

    @Override
    public void assignRole(Long adminId, List<Long> roleIds) {

        //先删除用户之前的角色
        adminRoleMapper.deleteByAdminId(adminId);
        //再重新分配角色(1.在此处遍历集合2.在数据库遍历roleIds集合)
        adminRoleMapper.assignRole(adminId,roleIds);
    }

    @Override
    public Admin findAdminByUsername(String username) {
        return null;
    }


    @Override
    public Map<String, List<Role>> findRolesByAdminId(Long adminId) {
        //1.查询所有角色
        List<Role> allRoleList = roleMapper.findAll();
        //2.查询用户已分配的角色id列表
        List<Long> roleIdList = adminRoleMapper.findRoleIdListByAdminId(adminId);
        //3.创建两个List集合分别存储用户已分配和未分配的角色
        //未分配角色列表
        List<Role> unAssignRoleList = new ArrayList<>();
        //已分配角色列表
        List<Role> assignRoleList = new ArrayList<>();
        //4.筛选用户已分配和未分配角色

        for (Role role : allRoleList) {
            if (roleIdList.contains(role.getId())){
                //已分配
                assignRoleList.add(role);
            }else {
                //未分配
                unAssignRoleList.add(role);
            }
        }
        Map<String,List<Role>> roleMap = new HashMap<>();

        roleMap.put("unAssignRoleList",unAssignRoleList);
        roleMap.put("assignRoleList",assignRoleList);

        return roleMap;
    }
}
